 # 文件：res://scripts/Kitchen.gd
# Implementation of TECH-T006
extends Node2D

# 预加载卡牌场景
const CardScene = preload("res://scenes/Card.tscn")

# 导出变量，便于在编辑器中连接节点
@export var hand_container: HBoxContainer
@export var energy_label: Label

# 手牌数组，存储当前手牌实例
var hand_cards: Array = []

#  Called when the node enters the scene tree for the first time.
func _ready():
	print("Kitchen scene _ready() called")
	
	# 初始化UI
	initialize_ui()
	
	# 连接能量变化信号
	var global_singleton = get_node("/root/Global")
	if global_singleton:
		global_singleton.energy_changed.connect(_on_energy_changed)
		print("Energy change signal connected")
	else:
		print("ERROR: Global singleton not found for energy signal")
	
	# 初始化手牌
	initialize_hand()
	
	# 临时调试：延迟检查手牌状态
	call_deferred("_debug_hand_status")

# 初始化UI元素
func initialize_ui():
	# 初始化能量显示
	update_energy_display()

# 更新能量显示
func update_energy_display():
	var global_singleton = get_node("/root/Global")
	if energy_label and global_singleton:
		energy_label.text = "能量: %d/%d" % [global_singleton.current_energy, global_singleton.max_energy]
		print("Energy display updated: ", global_singleton.current_energy, "/", global_singleton.max_energy)
	elif not energy_label:
		print("WARNING: energy_label is null")
	elif not global_singleton:
		print("WARNING: Global singleton is null")

# 初始化手牌
func initialize_hand():
	print("initialize_hand() called")
	
	# 确保手牌容器已连接
	if not hand_container:
		push_error("Hand container not assigned!")
		print("ERROR: hand_container is null - please connect it in the editor!")
		return
	
	print("Hand container found, proceeding with card initialization")
	
	# 清空现有手牌（如果有）
	for card in hand_cards:
		card.queue_free()
	hand_cards.clear()
	
	# 定义初始手牌的卡牌ID（从Global.card_database中选取）
	var initial_hand_ids = [
		"chicken_breast", 
		"butter", 
		"stir_fry",
		"wagyu_beef",
		"roast"
	]
	
	# 使用get_node访问Autoload单例
	var global_singleton = get_node("/root/Global")
	if not global_singleton:
		push_error("Global singleton not found!")
		print("ERROR: Global singleton not found!")
		return
	
	print("Global singleton found, card database size: ", global_singleton.card_database.size())
	
	# 遍历ID数组，创建卡牌实例
	for card_id in initial_hand_ids:
		# 从全局数据库获取卡牌数据
		var card_data = global_singleton.card_database.get(card_id)
		if card_data:
			print("Creating card instance for: ", card_id)
			# 实例化卡牌场景
			var card_instance = CardScene.instantiate()
			# 将卡牌添加到手牌容器
			hand_container.add_child(card_instance)
			# 初始化卡牌数据
			card_instance.initialize(card_data)
			# 存储卡牌引用
			hand_cards.append(card_instance)
			
			# 连接卡牌的点击信号
			card_instance.card_clicked.connect(_on_card_clicked)
			print("Card added to hand: ", card_data.get("name"))
			print("Card instance position: ", card_instance.position)
			print("Card instance size: ", card_instance.size)
			print("Hand container child count: ", hand_container.get_child_count())
			print("Card click signal connected for: ", card_data.get("name"))
		else:
			push_error("Card data not found for ID: " + card_id)
			print("ERROR: Card data not found for ID: ", card_id)

# 卡牌点击处理函数
func _on_card_clicked(card_ref):
	print("尝试打出: ", card_ref.card_data.get("name"))
	
	var energy_cost = card_ref.card_data.get("energy_cost", 1)
	
	# 尝试消耗能量
	var global_singleton = get_node("/root/Global")
	if global_singleton:
		if global_singleton.use_energy(energy_cost):
			print("成功打出卡牌!")
			# 这里可以添加实际的打牌逻辑
			# play_card_to_kitchen(card_ref)
		else:
			print("能量不足，无法打出此卡牌")
	else:
		print("ERROR: Global singleton not found for energy check")

# 临时调试函数
func _debug_hand_status():
	print("=== DEBUG: Hand Status ===")
	print("Hand container exists: ", hand_container != null)
	if hand_container:
		print("Hand container child count: ", hand_container.get_child_count())
		print("Hand container position: ", hand_container.position)
		print("Hand container size: ", hand_container.size)
		print("Hand container visible: ", hand_container.visible)
		
		for i in range(hand_container.get_child_count()):
			var child = hand_container.get_child(i)
			print("Child ", i, ": ", child.name, " - Position: ", child.position, " - Size: ", child.size, " - Visible: ", child.visible)
			if child.has_method("_on_gui_input"):
				print("  - Has _on_gui_input method")
			if child.has_signal("card_clicked"):
				print("  - Has card_clicked signal")
			print("  - Color: ", child.color if child.has_method("get_color") else "N/A")
	
	print("Hand cards array size: ", hand_cards.size())
	print("========================")

# 能量变化信号处理函数
func _on_energy_changed(current_energy, max_energy):
	print("能量变化: ", current_energy, "/", max_energy)
	update_energy_display()

# 测试按钮处理函数
func _on_test_use_energy_button_pressed():
	var global_singleton = get_node("/root/Global")
	if global_singleton:
		global_singleton.use_energy(1)
	else:
		print("ERROR: Global singleton not found")

func _on_test_reset_energy_button_pressed():
	var global_singleton = get_node("/root/Global")
	if global_singleton:
		global_singleton.reset_energy()
		print("能量已重置")
	else:
		print("ERROR: Global singleton not found") 